<template>
  <view class="test-container">
    <view class="header">
      <text class="title">动态Token广告接口测试</text>
    </view>
    
    <!-- Token状态显示 -->
    <view class="token-status">
      <view class="status-item">
        <text class="status-label">登录状态:</text>
        <text class="status-value" :class="isLoggedIn ? 'success' : 'error'">
          {{ isLoggedIn ? '已登录' : '未登录' }}
        </text>
      </view>
      <view class="status-item" v-if="currentToken">
        <text class="status-label">Token:</text>
        <text class="status-value token-text">{{ currentToken.substring(0, 30) }}...</text>
      </view>
    </view>
    
    <view class="login-section" v-if="!isLoggedIn">
      <view class="section-title">请先登录获取Token</view>
      <view class="input-group">
        <input v-model="loginForm.username" placeholder="用户名" class="input" />
        <input v-model="loginForm.password" type="password" placeholder="密码" class="input" />
        <input v-model="loginForm.code" placeholder="验证码" class="input" v-if="captchaEnabled" />
      </view>
      <view class="captcha-section" v-if="captchaEnabled">
        <image :src="codeUrl" @click="getCode" class="captcha-img"></image>
        <text class="captcha-tip">点击图片刷新验证码</text>
      </view>
      <button @click="handleLogin" class="login-btn">登录获取Token</button>
    </view>
    
    <view class="test-section" v-if="isLoggedIn">
      <view class="section-title">广告接口测试</view>
      <view class="button-group">
        <button @click="testAdvertisementAPI" class="test-btn">获取广告列表</button>
        <button @click="handleLogout" class="logout-btn">退出登录</button>
      </view>
      
      <view class="result-section" v-if="apiResult">
        <view class="result-title">API响应结果:</view>
        <view class="result-content">
          <text class="result-text">{{ apiResult }}</text>
        </view>
      </view>
      
      <view class="banner-section" v-if="bannerList.length > 0">
        <view class="section-title">轮播图数据预览:</view>
        <view class="banner-grid">
          <view class="banner-item" v-for="(item, index) in bannerList" :key="index">
            <image :src="item.image" class="banner-image" mode="aspectFill"></image>
            <view class="banner-info">
              <text class="banner-title">{{ item.title }}</text>
              <text class="banner-id">ID: {{ item.id }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 技术说明 -->
      <view class="tech-info">
        <view class="section-title">技术实现说明:</view>
        <view class="info-item">
          <text class="info-text">✅ 使用迭代猫系统的登录API获取Token</text>
        </view>
        <view class="info-item">
          <text class="info-text">✅ Token自动存储在uni.getStorageSync('App-Token')</text>
        </view>
        <view class="info-item">
          <text class="info-text">✅ request工具自动添加Authorization头</text>
        </view>
        <view class="info-item">
          <text class="info-text">✅ 广告API使用动态Token，无需硬编码</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getCodeImg } from '@/api/login'
import { listAdvertisement } from '@/api/advertisement'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { API_CONFIG } from '@/api/config.js'

export default {
  data() {
    return {
      isLoggedIn: false,
      currentToken: '',
      codeUrl: "",
      captchaEnabled: true,
      loginForm: {
        username: "admin",
        password: "admin123",
        code: "",
        uuid: ""
      },
      apiResult: "",
      bannerList: []
    }
  },
  
  onLoad() {
    // 检查是否已登录
    this.checkLoginStatus()
  },
  
  methods: {
    // 检查登录状态
    checkLoginStatus() {
      const token = getToken()
      if (token) {
        this.isLoggedIn = true
        this.currentToken = token
        console.log('已登录，Token:', token.substring(0, 30) + '...')
      } else {
        this.isLoggedIn = false
        this.currentToken = ''
        this.getCode()
      }
    },
    
    // 获取验证码
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = 'data:image/gif;base64,' + res.img
          this.loginForm.uuid = res.uuid
        }
      }).catch(error => {
        console.error('获取验证码失败:', error)
        this.apiResult = '获取验证码失败: ' + JSON.stringify(error)
      })
    },
    
    // 登录
    async handleLogin() {
      if (!this.loginForm.username || !this.loginForm.password) {
        uni.showToast({ title: '请输入用户名和密码', icon: 'none' })
        return
      }
      
      if (this.captchaEnabled && !this.loginForm.code) {
        uni.showToast({ title: '请输入验证码', icon: 'none' })
        return
      }
      
      try {
        uni.showLoading({ title: '登录中...' })
        
        // 使用Vuex store的Login action
        await this.$store.dispatch('Login', this.loginForm)
        
        // 登录成功后获取用户信息
        await this.$store.dispatch('GetInfo')
        
        // 更新登录状态
        this.checkLoginStatus()
        
        uni.hideLoading()
        uni.showToast({ title: '登录成功！', icon: 'success' })
        
        
      } catch (error) {
        uni.hideLoading()
        console.error('登录失败:', error)
        this.apiResult = '登录失败: ' + (error.message || JSON.stringify(error))
        uni.showToast({ title: '登录失败', icon: 'error' })
        if (this.captchaEnabled) {
          this.getCode()
        }
      }
    },
    
    // 登出
    async handleLogout() {
      try {
        uni.showLoading({ title: '退出中...' })
        
        // 使用Vuex store的LogOut action
        await this.$store.dispatch('LogOut')
        
        // 更新登录状态
        this.checkLoginStatus()
        
        // 清空数据
        this.apiResult = ''
        this.bannerList = []
        
        uni.hideLoading()
        uni.showToast({ title: '已退出登录', icon: 'success' })
        
      } catch (error) {
        uni.hideLoading()
        console.error('退出失败:', error)
        uni.showToast({ title: '退出失败', icon: 'error' })
      }
    },
    
    // 测试广告接口
    async testAdvertisementAPI() {
      try {
        uni.showLoading({ title: '获取广告数据...' })
        
        console.log('当前Token:', this.currentToken.substring(0, 30) + '...')
        
        const response = await listAdvertisement({
          adType: '1',  // 轮播图类型
          status: '0',  // 启用状态
          orgId: '115'  // 组织ID
        })
        
        uni.hideLoading()
        
        this.apiResult = JSON.stringify(response, null, 2)
        
        if (response.code === 200 && response.rows && response.rows.length > 0) {
          this.bannerList = response.rows.map(item => {
            // 直接使用图片URL，不需要拼接服务器地址（七牛云存储）
            let imageUrl = item.adImage || 'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=800&h=400&fit=crop'
            
            return {
              id: item.adId,
              image: imageUrl,
              title: item.adTitle || '默认标题',
              url: item.adUrl || '#'
            }
          })
          uni.showToast({ title: `获取到${this.bannerList.length}条广告数据`, icon: 'success' })
        } else {
          uni.showToast({ title: '暂无广告数据', icon: 'none' })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('获取广告数据失败:', error)
        this.apiResult = '获取广告数据失败: ' + (error.message || JSON.stringify(error))
        uni.showToast({ title: '获取广告数据失败', icon: 'error' })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.test-container {
  padding: 40rpx;
  background: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 40rpx;
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.login-section, .test-section {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.input-group {
  margin-bottom: 30rpx;
  
  .input {
    width: 100%;
    height: 80rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 10rpx;
    padding: 0 20rpx;
    margin-bottom: 20rpx;
    font-size: 28rpx;
  }
}

.captcha-section {
  margin-bottom: 30rpx;
  
  .captcha-img {
    width: 200rpx;
    height: 80rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 10rpx;
  }
}

.login-btn, .test-btn {
  width: 100%;
  height: 80rpx;
  background: #007aff;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  font-size: 30rpx;
  margin-bottom: 20rpx;
}

.result-section {
  margin-top: 40rpx;
  
  .result-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .result-text {
    font-size: 24rpx;
    color: #666;
    background: #f8f8f8;
    padding: 20rpx;
    border-radius: 10rpx;
    word-break: break-all;
  }
}

.banner-section {
  margin-top: 40rpx;
  
  .banner-item {
    margin-bottom: 30rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 10rpx;
    overflow: hidden;
    
    .banner-image {
      width: 100%;
      height: 300rpx;
    }
    
    .banner-title {
      display: block;
      padding: 20rpx;
      font-size: 28rpx;
      color: #333;
    }
  }
}
</style>